﻿using DingChiServiceApp.db;
using DingChiServiceApp.entity;
using DingChiServiceApp.helper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace DingChiServiceApp
{
    public partial class MainWindow : Window
    {
        #region Time variables

        public DispatcherTimer LogTimer;

        public readonly static string serviceName = "dingchi2.0";
        public readonly static string displayName = "滇池水务数据服务";
        public readonly static string description = "滇池水务污泥调运系统与滇管局数据服务";
        public LogHelper.LogInfo lastLog;
        #endregion

        #region variables


        #endregion

        public MainWindow()
        {
            InitializeComponent();
        }

        #region window event
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitTimer();
        }

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            LogTimer?.Start();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 考虑删除七天以前的日志文件
            DeleteOldLogFile();
            DisposeTime();
        }

        #endregion

        #region Time 

        private void InitTimer()
        {
            if (LogTimer == null)
            {
                LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();

                LogTimer = new DispatcherTimer(DispatcherPriority.Background)
                {
                    Interval = TimeSpan.FromSeconds(localConfig.interval)
                };
            }
            LogTimer.Tag = "滇池水务";
            LogTimer.Tick += LogTimer_Tick;

        }
        //显示日志
        private void LogTimer_Tick(object sender, EventArgs e)
        {
            //TODO 去读取文件 
            var log = LogHelper.Logs.LastOrDefault();
            if (log == null) return;
            if (lastLog == null || lastLog.id != log.id)
            {
                lastLog = log;
                ShowMsg(log.msg, log.errLevel);
            }
            else
            {
                if (lastLog.id != log.id)
                {
                    ShowMsg(log.msg, log.errLevel);
                }
            }
            lastLog = log;

            if (LogHelper.Logs.Count > 5000)
            {
                LogHelper.Logs.Clear();
            }
        }


        private void DeleteOldLogFile()
        {
            try
            {
                string path = GlobalConstract.logPath;
                DirectoryInfo dirInfo = new DirectoryInfo(path);
                if (dirInfo.Exists)
                {
                    var fs = dirInfo.GetFiles();
                    for (int i = 0; i < fs.Length; i++)
                    {
                        var fi = fs[i];
                        if ((DateTime.Now - fi.CreationTime).TotalDays >= 7) File.Delete(fi.FullName);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.FileLog("删除七天以前的日志文件 异常:" + ex.Message);
            }
        }


        private void DisposeTime()
        {
            LogTimer?.Stop();
            LogTimer.IsEnabled = false;
            LogTimer = null;
        }

        #endregion

        private void StartBtn_Click(object sender, RoutedEventArgs e)
        {
            ServiceHelper.StartService(serviceName);
        }

        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            ServiceHelper.StopService(serviceName);
        }

        private void StautsBtn_Click(object sender, RoutedEventArgs e)
        {
            ServiceControllerStatus status = ServiceHelper.GetServiceStatus(serviceName);
            ShowMsg(serviceName + " Status:" + status.ToString());
        }

        private void InstallBtn_Click(object sender, RoutedEventArgs e)
        {
            ServiceHelper.Install(serviceName, displayName, description);
        }

        private void UnIinstallBtn_Click(object sender, RoutedEventArgs e)
        {
            ServiceHelper.UnInstall(serviceName);
        }

        private void ShowMsg(string msg, int errlevel = 0)
        {
            if (logLv.Items.Count > 5000)
            {
                logLv.Items.Clear();
            }
            ListViewItem vi = new ListViewItem()
            {
                Content = msg,
            };
            if (errlevel == 1)
            {
                vi.Foreground = Brushes.Red;
            }
            else if (errlevel == -1)
            {
                vi.Foreground = Brushes.LightGray;
            }
            else
            {
                vi.Foreground = Brushes.Black;
            }
            this.logLv.Items.Add(vi);
            this.logLv.ScrollIntoView(vi);
        }
        #region 数据源 配制
        private void DataSourceSettingMi_Click(object sender, RoutedEventArgs e)
        {
            this.configPopup.IsOpen = !this.configPopup.IsOpen;
        }

        private void ConfigPopup_Opened(object sender, EventArgs e)
        {
            LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();

            this.DataSourceTb.Text = localConfig.dataSource;
            this.protTb.Text = localConfig.port.ToString();
            this.DbNameTb.Text = localConfig.dbName;
            this.UserIdTb.Text = localConfig.userID;
            this.PwdTb.Text = localConfig.pwd;
            this.interialTb.Text = localConfig.interval.ToString();
            this.rowsTb.Text = localConfig.maxRows.ToString();
        }

        private void ConfigPopup_Closed(object sender, EventArgs e)
        {
            this.DataSourceTb.Text = String.Empty;
            this.protTb.Text = String.Empty;
            this.DbNameTb.Text = String.Empty;
            this.UserIdTb.Text = String.Empty;
            this.PwdTb.Text = String.Empty;
            this.interialTb.Text = String.Empty;
            this.rowsTb.Text = String.Empty;
        }

        private void SaveConfig_Click(object sender, RoutedEventArgs e)
        {
            LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();

            localConfig.dataSource = this.DataSourceTb.Text;
            localConfig.port = Convert.ToInt32(this.protTb.Text);
            localConfig.dbName = this.DbNameTb.Text;
            localConfig.userID = this.UserIdTb.Text;
            localConfig.pwd = this.PwdTb.Text;
            localConfig.maxRows = Convert.ToInt32(this.rowsTb.Text);
            localConfig.interval = Convert.ToInt32(this.interialTb.Text);

            int res = LocalConfigJsonDao.Instance.Update(localConfig);
            if (res > 0)
            {
                this.configPopup.IsOpen = false;
                MessageBox.Show("保存成功！");
            }
            else
            {
                this.configPopup.IsOpen = false;
                MessageBox.Show("保存失败！");
            }
        }

        private void CloseConfigbtn_Click(object sender, RoutedEventArgs e)
        {
            this.configPopup.IsOpen = false;
        }

        #endregion

        /// <summary>
        /// 统计已经上传数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StatisticsBtn_Click(object sender, RoutedEventArgs e)
        {
            int count = new HaulBillDao().CountIsUp();
            string msg = "已经上传: " + count + " 条。";

            ListViewItem vi = new ListViewItem
            {
                Content = msg,
                FontSize = 14,
                Foreground = Brushes.Green
            };
            this.logLv.Items.Add(vi);
            this.logLv.ScrollIntoView(vi);
        }
    }
}